package lee.vioson.ebook.ui.components

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import coil.compose.AsyncImage
import kotlinx.coroutines.flow.launchIn
import lee.vioson.ebook.R
import lee.vioson.ebook.data.AppContainer
import lee.vioson.ebook.ui.AppTheme
import lee.vioson.ebook.viewmodels.ReadPageViewModel
import lee.vioson.remotedata.bean.ChapterInfo
import lee.vioson.remotedata.bean.DownloadState

@Composable
fun ReadPage(
    appContainer: AppContainer,
    bookId: String,
    chapterInfo: ChapterInfo,
    viewModel: ReadPageViewModel = viewModel(
        factory = viewModelFactory {
            initializer {
                ReadPageViewModel(
                    appContainer,
                    bookId,
                    chapterInfo.chapterId
                )
            }
        }
    )
) {
    val configuration = LocalConfiguration.current
    val screenHeight = configuration.screenHeightDp.dp

    val state by viewModel.state.collectAsState()
    val scope = rememberCoroutineScope()
    LaunchedEffect(key1 = chapterInfo, block = {
        viewModel.checkCachedAndDownload(chapterInfo).launchIn(scope)
    })
    when (state.downloadState) {
        is DownloadState.InProgress -> {
            ItemLoading(
                progress = (state.downloadState as DownloadState.InProgress).progress,
                text = stringResource(
                    id = R.string.has_be_downloaded,
                    (state.downloadState as DownloadState.InProgress).progress
                )
            )
        }

        is DownloadState.Error -> {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(screenHeight),
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = stringResource(
                        id = R.string.download_error,
                        (state.downloadState as DownloadState.Error).throwable.localizedMessage
                            ?: ""
                    ),
                    fontSize = 14.sp,
                    color = AppTheme.colors.onBackground
                )
            }
        }

        is DownloadState.Cached,
        is DownloadState.Success -> {
            if (state.extracting) {
                ItemLoading(text = stringResource(id = R.string.extracting_data))
            } else {
                state.picList.forEach { pic ->
                    AsyncImage(
                        model = pic,
                        contentDescription = "book page",
                        modifier = Modifier
                            .fillMaxWidth()
                            .background(Color.Red.copy(alpha = 0.3f)),
                        contentScale = ContentScale.FillWidth
                    )
                }
            }
        }
    }
}

@Composable
fun ItemLoading(progress: Int? = null, text: String? = null) {
    val configuration = LocalConfiguration.current
    val screenHeight = configuration.screenHeightDp.dp
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .height(screenHeight),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        if (progress != null) {
            CircularProgressIndicator(progress = progress / 100F)
        } else {
            CircularProgressIndicator()
        }
        if (text != null) {
            Text(
                text = text,
                fontSize = 14.sp,
                color = AppTheme.colors.onBackground
            )
        }
    }
}